<template>
  <div class="app">
    <template v-if="isAuthenticated">
      <div class="chat-app">
        <div class="chat-header">
          <h2>Vue 聊天 {{ selectedUser ? `- 与 ${selectedUser.nick_name} 聊天中` : '(群聊)' }}</h2>
          <button @click="logout" class="logout-btn">退出</button>
        </div>
        <div class="main-content">
          <UserList 
            :users="onlineUsers"
            :selected-user="selectedUser" 
            @select-user="handleUserSelect"
          />
          <div class="chat-container">
            <ChatWindow :messages="filteredMessages" />
            <ChatInput 
              @send-message="sendMessage"
              @send-image="sendImage"
              @send-voice="sendVoice"
            />
          </div>
        </div>
      </div>
    </template>
    <template v-else>
      <LoginForm @login="handleLogin" />
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { authService } from './services/api';
import { wsService } from './services/websocket';
import { userService } from './services/userService';
import ChatWindow from './components/ChatWindow.vue';
import ChatInput from './components/ChatInput.vue';
import UserList from './components/UserList.vue';
import LoginForm from './components/LoginForm.vue';

const isAuthenticated = ref(!!localStorage.getItem('token'));
const messages = ref([]);
const onlineUsers = ref([]);

const handleLogin = async (credentials) => {
  try {
    await authService.login(credentials.username, credentials.password);
    isAuthenticated.value = true;
    wsService.connect('login');
  } catch (error) {
    alert(error.message);
  }
};

const logout = () => {
  authService.logout();
  wsService.disconnect();
  isAuthenticated.value = false;
  messages.value = [];
};

const selectedUser = ref(null)
const currentUser = computed(() => userService.getUser())

// 过滤当前聊天消息
const filteredMessages = computed(() => {
  if (!selectedUser.value) {
    // 群聊消息
    return messages.value.filter(msg => !msg.to)
  }
  // 私聊消息
  return messages.value.filter(msg => 
    (msg.from === selectedUser.value.uid && msg.to === currentUser.value.uid) ||
    (msg.from === currentUser.value.uid && msg.to === selectedUser.value.uid)
  )
})

const handleUserSelect = (user) => {
  // 如果点击当前选中的用户，则取消选择（回到群聊）
  if (selectedUser.value && selectedUser.value.uid === user.uid) {
    selectedUser.value = null
  } else {
    selectedUser.value = user
  }
}

const sendMessage = (content) => {
  console.log('currentUser:',currentUser.value)
  console.log('selectedUser:',selectedUser.value)
  const message = {
    content,
    type: 'text',
    to: selectedUser.value?selectedUser.value.uid:null
  }
  wsService.sendMessage(message)
  // 添加到本地消息列表
  messages.value.push({
    ...message,
    from: currentUser.value.uid,
    from_name: currentUser.value.nick_name,
    from_head_img: currentUser.value.head_img,
    timestamp: new Date().getTime()
  })
}

const sendImage = async (file) => {
  try {
    const url = await messageService.uploadImage(file);
    wsService.sendMessage(url, 'image');
  } catch (error) {
    alert('图片上传失败');
  }
};

const sendVoice = (audioBlob) => {
  // 实现语音消息发送逻辑
};

onMounted(() => {
  if (isAuthenticated.value) {
    wsService.connect();
  }

  wsService.onMessage((message) => {
    messages.value.push(message);
  });

  wsService.onUserStatus((users) => {
    console.log('收到用户状态更新:', users)
    onlineUsers.value = users || []
  });
});

onUnmounted(() => {
  if (wsService.ws) {
    wsService.ws.close();
  }
});
</script>

<style scoped>
.app {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
}

.chat-app {
  width: 1000px;
  height: 80vh;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 15px;
  background-color: #07c160;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 8px 8px 0 0;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.logout-btn {
  padding: 5px 10px;
  background: transparent;
  border: 1px solid white;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}

.logout-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}
</style>